package cn.tedu.blog.server.controller.system;

import cn.tedu.blog.server.config.WebSocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/webSocketToUser/{id}", configurator = WebSocketConfig.class)
public class WebSocketToUser {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    private static ConcurrentHashMap<Long, WebSocketToUser> webSocketSet = new ConcurrentHashMap<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private static Session session;

    //指定的sid，具有唯一性
    private static Long sid = null;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("id") Long id, Session session, EndpointConfig config) {
        //获取WebsocketConfig.java中配置的“sessionId”信息值
        String httpSessionId = (String) config.getUserProperties().get("sessionId");
        this.session = session;
        this.sid = id;

        webSocketSet.put(sid, this);     //加入set中
        addOnlineCount();           //在线数加1
        log.error("用戶" + sid + "加入！当前在线人数为" + getOnlineCount());
        log.error("用戶" + sid + "加入！当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.err.println("来自客户端的消息:" + message);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }


    /**
     * 实现服务器单个用户主动推送
     */
    public void sendMessageByUserId(Long id,String message) throws IOException {
//        this.session.getBasicRemote().sendText(message);
        Set<Map.Entry<Long, WebSocketToUser>> entrySet = webSocketSet.entrySet();
        for (Map.Entry<Long, WebSocketToUser> longWebSocketToUserEntry : entrySet) {
            if (longWebSocketToUserEntry.getKey() == id){
                this.session.getBasicRemote().sendText(message);
                return;
            }
        }
    }


    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public boolean sendToUser(String message, Long sendUserId) throws IOException {
        if (webSocketSet.get(sendUserId) != null) {
            if (!sid.equals(sendUserId)) {
                return false;
                //webSocketSet.get(sendUserId).sendMessage("用户" + sendUserId + "发来消息：" + message);
            } else {
                webSocketSet.get(sendUserId).sendMessage(message);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return true;
            }
        } else {
            //如果用户不在线则返回不在线信息给自己
            return false;
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketToUser.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketToUser.onlineCount--;
    }
}
